package com.young.controller;

import com.alibaba.fastjson.JSON;
import com.young.config.MailProperties;
import com.young.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import com.young.util.CodeUtill;

@RestController
public class MailController {
    @Autowired
    private JavaMailSenderImpl mailSender;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private MailProperties mailProperties;
    @RequestMapping(value = "/sendMail",method = RequestMethod.POST)
    public String sendMail(@RequestParam(value = "to",required = true)String to)throws Exception{
        MimeMessage message=mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(message);
        helper.setSubject("验证码通知：");
        helper.setFrom(mailProperties.getUsername());
        helper.setTo(to);
        String code= CodeUtill.getCode();
        //设置到redis中，并设置超时时间60秒
        redisUtil.set("code",code,60L);
        helper.setText("您的验证码是<h2>"+code+"</h2>,请不要告诉其他人");
        mailSender.send(message);
        return "发送成功";
    }
    @RequestMapping(value = "/verify",method = RequestMethod.POST)
    public String verify(@RequestParam(value = "code",required = true)String code){
        String code1= JSON.parseObject(redisUtil.get("code"),String.class);
        if(code.equals(code1)){
            return "验证成功";
        }
        return "验证失败";
    }
}


